package mrHunter.web;

import mrHunter.UserInf;
import mrHunter.data.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@RequestMapping("/")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(method = GET)
    public String home(Model model) {
        return "home";
    }

    @RequestMapping(value = "/exit",method = GET)
    public String doExit(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/";
    }

    @RequestMapping(value = "/register",method = GET)
    public String showRegistrationForm(){
        return "register";
    }

    @RequestMapping(value = "/register",method = POST)
    @ResponseBody
    public Map<String, Object> processRegistration(UserInf userInf){
        Map<String, Object> result=new HashMap<>();
        int[] currentLevel={1,1,1,1};
        userInf.setCurrentLevel(currentLevel);
        boolean isSave=userRepository.save(userInf);
        if(isSave)
        {
            result.put("result","SUCCESS");
        }
        else
            {
            result.put("result","FAILURE");
        }
        return result;
    }

    @RequestMapping(value = "/login", method = GET)
    public String showLoginForm(){
        return "login";
    }

    @RequestMapping(value = "/login", method = POST)
    @ResponseBody
    public Map<String, Object> processLogin(HttpServletRequest request, UserInf userInf){
        Map<String, Object> result=new HashMap<>();
        boolean legitimacy = userRepository.passwordCheck(userInf.getUsername(),userInf.getPassword());
        if (legitimacy) {
            request.getSession().setAttribute("user", userRepository.findByUserName(userInf.getUsername()));
            result.put("result","SUCCESS");
        } else {
            result.put("result","FAILURE");
        }
        return result;
    }


    @RequestMapping(value = "/{username}",method = GET)
    public String showUserProfile(@PathVariable String username, Model model){
        UserInf userInf=userRepository.findByUserName(username);
        model.addAttribute(userInf);
        return "profile";
    }

    @RequestMapping(value = "/{username}",method = POST)
    public String gotoLogin(@PathVariable String username, Model model){
        return "redirect:/login";
    }


}
